package com.sky.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sky.context.BaseContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MQ的自动填充
 *
 * @Author mr.lcc
 * @Data 2025/5/19 13:52
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 拦截新增方法
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置createTime
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 设置更新人
        this.strictInsertFill(metaObject, "createUser", String.class, getLoginName());
    }

    /**
     * 拦截更新方法
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 设置createTime
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 设置更新人
        this.strictUpdateFill(metaObject, "updateUser", String.class, getLoginName());
    }

    /**
     * 获取用户Id
     *
     * @return
     */
    private String getLoginName() {
        Long currentId = BaseContext.getCurrentId();
        if (currentId != null) {
            return currentId.toString();
        }
        return "1";
    }
}
